<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { postAction } from '@api/manage'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'
import { JVXETypes } from '@comp/jeecg/JVxeTable'
import dayjs from 'dayjs'

export default {
  name: 'OutboundRecordWithItemForm',
  mixins: [JVxeTableModelMixin],
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      validatorRules: {
        outboundDate: [
          { required: true, message: '请输入出库日期!' }
        ]
      },
      // 出库记录明细表
      outboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            type: JVXETypes.normal,
            width: '110px'
          },
          {
            title: '物料编码',
            key: 'materialCode',
            type: JVXETypes.normal,
            width: '110px'
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            minWidth: '180px'
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            type: JVXETypes.normal,
            width: '90px'
          },
          {
            title: '单位',
            key: 'unit_dictText',
            type: JVXETypes.normal,
            dictCode: 'ji_unit',
            width: '60px'
          },
          {
            title: '库存数量',
            key: 'quantity',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '辅单位',
            key: 'secondaryUnit_dictText',
            type: JVXETypes.normal,
            dictCode: 'zl_unit',
            width: '70px'
          },
          {
            title: '辅数量',
            key: 'secondaryQuantity',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '生产日期',
            key: 'productionDate',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '限用日期',
            key: 'expirationDate',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '批次号',
            key: 'batchNumber',
            type: JVXETypes.normal,
            width: '100px'
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '储位',
            key: 'storageLocation',
            type: JVXETypes.normal,
            width: '150px'
          },
          {
            title: '质检状态',
            key: 'qualityInspectionStatus_dictText',
            type: JVXETypes.normal,
            width: '80px'
          },
          {
            title: '通知出库数量',
            key: 'notifyOutboundQuantity',
            type: JVXETypes.normal,
            width: '150px'
          }
        ]
      },
      url: {
        add: '/wms/outbound/outbound-record/add',
        edit: '/wms/outbound/outbound-record/edit',
        outboundOrderItem: {
          list: '/wms/outbound/outbound-order/queryOutboundOrderItemByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  methods: {
    insert(record) {
      if (!record) {
        return
      }
      this.insertBefore()
      this.model = Object.assign({}, record[0])
      this.model.outboundDate = dayjs().format('YYYY-MM-DD')
      this.insertAfter()
    },
    insertBefore() {
      this.outboundRecordItemTable.dataSource = []
    },
    insertAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.outboundOrderItem.list, params, this.outboundRecordItemTable, (res) => {
          if (this.outboundRecordItemTable.dataSource && this.outboundRecordItemTable.dataSource.length > 0) {
            this.outboundRecordItemTable.dataSource.forEach(item => {
              item.notifyOutboundQuantity = item.quantity
            })
          }
        })
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        outboundOrderItemList: allValues.tablesValue[0].tableData
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      if (!this.outboundRecordItemTable.dataSource.length) {
        return
      }
      const errMap = await this.$refs.outboundRecordItem.validateTable()
      if (errMap) {
        return
      }
      const formData = {
        ...this.model,
        id: null,
        createBy: null,
        createTime: null,
        outboundRecordItemList: this.outboundRecordItemTable.dataSource.map(item => {
          return {
            ...item,
            id: null,
            createBy: null,
            createTime: null
          }
        })
      }
      this.request(formData)
    },
    request(formData) {
      this.confirmLoading = true
      postAction(this.url.add, formData)
        .then((res) => {
          if (res.success) {
            this.model.dataId = res.message
            this.applySubmit(this.model)
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }
      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
        } else {
          const params = Object.assign({ dataId: record.dataId }, record)
          definitionStartByDataId(record.dataId, 'outboundRecordService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
              this.$emit('ok')
            })
        }
      })
    }
  }
}
</script>

<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="出库记录单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="entryNumber">
              <a-input v-model="model.recordNumber" placeholder="保存自动生成" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <!--
          <a-col :span="8">
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="approvalFlow">
              <j-dict-select-tag
                type="list"
                v-model="model.approvalFlow"
                dictCode="outbound_record_flow"
                placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          -->
          <a-col :span="8">
            <a-form-model-item label="出库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="outboundDate">
              <j-date placeholder="请选择出库日期" v-model="model.outboundDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <j-vxe-table
      keep-source
      ref="outboundRecordItem"
      :loading="outboundRecordItemTable.loading"
      :columns="outboundRecordItemTable.columns"
      :dataSource="outboundRecordItemTable.dataSource"
      :maxHeight="300"
      :disabled="formDisabled"
      :rowNumber="true"
      :rowSelection="false"
      :toolbar="false"
    >
    </j-vxe-table>
  </a-spin>
</template>

<style scoped>

</style>